package com.woniuxy.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.system.common.Result;
import com.woniuxy.system.entity.UrlPermission;
import com.woniuxy.system.model.vo.PageVo;
import com.woniuxy.system.model.vo.PermissonMenuVo;
import com.woniuxy.system.service.IUrlPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单和接口权限定义 前端控制器
 * </p>
 *
 * @author 作者
 * @since 2023-10-13
 */
@RestController
@RequestMapping("/urlPermission")
public class UrlPermissionController {

    @Autowired
    private IUrlPermissionService urlPermissionService;

    @GetMapping("/findPermissions")
    public Result findPermissions(Long managerId) {
        List<PermissonMenuVo> list = urlPermissionService.findPermissionsByManagerId(managerId);
        return Result.ok(list);
    }

    @GetMapping("/findAll")
    public Result findAll(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize, String name) {
        PageVo pageVo = urlPermissionService.findAll(pageNum,pageSize,name);
        return Result.ok(pageVo);
    }

    @GetMapping("/findFirstLevelMenu")
    public Result findFirstLevelMenu() {
        // 查询所有parent_id是-1的菜单，父菜单
        List<UrlPermission> list = urlPermissionService.list(
                Wrappers.lambdaQuery(UrlPermission.class)
                        .eq(UrlPermission::getParentId, -1));
        return Result.ok(list);
    }


    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody UrlPermission urlPermission) {
        if (urlPermission.getId() == null) {
            // 添加操作: 如果添加权限时候没有选择“父级菜单”，说明是一级菜单，需要设置parentId是-1
            if (urlPermission.getParentId() == null) {
                urlPermission.setParentId(-1L);
            }
            urlPermission.setInsertTime(new Date());
            urlPermissionService.save(urlPermission);
        } else {
            // 修改操作
            urlPermission.setUpdateTime(new Date());
            urlPermissionService.updateById(urlPermission);
        }
        return Result.ok();
    }

    // 权限树
    @GetMapping("/list")
    public Result list() {
        List<PermissonMenuVo> list = urlPermissionService.treeList();
        return Result.ok(list);
    }
}
